"""
候选人端演示模式API路由
移除登录验证，使用虚拟数据进行演示
"""

from fastapi import APIRouter, HTTPException, status, Query
from typing import List, Optional
import json
from datetime import datetime
import random

from ...demo_data_loader import demo_loader

router = APIRouter(prefix="/demo/candidate", tags=["候选人演示模式"])

@router.get("/jobs")
async def browse_jobs(
    skip: int = Query(0, description="跳过的记录数"),
    limit: int = Query(20, description="返回的记录数"),
    category: Optional[str] = Query(None, description="职位类别"),
    location: Optional[str] = Query(None, description="工作地点"),
    salary_min: Optional[int] = Query(None, description="最低薪资"),
    salary_max: Optional[int] = Query(None, description="最高薪资")
):
    """浏览职位"""
    try:
        jobs = await demo_loader.get_jobs(
            skip=skip,
            limit=limit,
            category=category,
            location=location,
            salary_min=salary_min,
            salary_max=salary_max
        )
        
        return {
            "status": "success",
            "data": jobs,
            "pagination": {
                "skip": skip,
                "limit": limit,
                "total": len(jobs)
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"浏览职位失败: {str(e)}"
        )

@router.get("/jobs/{job_id}")
async def get_job_detail(job_id: str):
    """获取职位详情"""
    try:
        job = await demo_loader.get_job_by_id(job_id)
        if not job:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="职位不存在"
            )
        
        return {
            "status": "success",
            "data": job
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取职位详情失败: {str(e)}"
        )

@router.get("/jobs/search")
async def search_jobs(
    q: str = Query(..., description="搜索关键词"),
    skip: int = Query(0, description="跳过的记录数"),
    limit: int = Query(20, description="返回的记录数")
):
    """搜索职位"""
    try:
        jobs = await demo_loader.search_jobs(q, skip=skip, limit=limit)
        
        return {
            "status": "success",
            "data": jobs,
            "query": q,
            "pagination": {
                "skip": skip,
                "limit": limit,
                "total": len(jobs)
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"搜索职位失败: {str(e)}"
        )

@router.get("/jobs/recommendations")
async def get_job_recommendations(
    candidate_id: str = Query("candidate_001", description="候选人ID"),
    limit: int = Query(10, description="推荐职位数量")
):
    """获取职位推荐"""
    try:
        candidate = await demo_loader.get_candidate_by_id(candidate_id)
        if not candidate:
            # 使用默认候选人
            candidate = {
                "category": "IT SOFTWARE",
                "skills": ["Python", "JavaScript", "数据分析"],
                "experience_years": 3,
                "expected_location": "北京"
            }
        
        # 根据候选人信息推荐职位
        jobs = await demo_loader.get_jobs(
            category=candidate.get("category"),
            location=candidate.get("expected_location"),
            limit=limit * 2  # 获取更多职位进行筛选
        )
        
        # 为每个职位计算匹配度
        candidate_skills = set(candidate.get("skills", []))
        recommended_jobs = []
        
        for job in jobs:
            job_skills = set(job.get("required_skills", []))
            skill_match = len(candidate_skills.intersection(job_skills)) / max(len(job_skills), 1) * 100
            
            # 经验匹配度
            required_exp = job.get("experience_min", 0)
            candidate_exp = candidate.get("experience_years", 0)
            exp_match = min(candidate_exp / max(required_exp, 1) * 100, 100)
            
            overall_match = (skill_match + exp_match) / 2
            
            if overall_match > 30:
                recommended_jobs.append({
                    **job,
                    "match_score": round(overall_match, 1),
                    "match_reasons": [
                        f"技能匹配度: {round(skill_match, 1)}%",
                        f"经验匹配度: {round(exp_match, 1)}%"
                    ]
                })
        
        # 按匹配度排序
        recommended_jobs.sort(key=lambda x: x['match_score'], reverse=True)
        
        return {
            "status": "success",
            "data": recommended_jobs[:limit],
            "total_recommended": len(recommended_jobs)
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取职位推荐失败: {str(e)}"
        )

@router.get("/profile/{candidate_id}")
async def get_candidate_profile(candidate_id: str):
    """获取候选人档案"""
    try:
        candidate = await demo_loader.get_candidate_by_id(candidate_id)
        if not candidate:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="候选人档案不存在"
            )
        
        return {
            "status": "success",
            "data": candidate
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取候选人档案失败: {str(e)}"
        )

@router.get("/resume/analysis/{candidate_id}")
async def analyze_my_resume(candidate_id: str):
    """分析我的简历"""
    try:
        analysis = await demo_loader.analyze_resume(candidate_id)
        if not analysis:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="简历分析数据不存在"
            )
        
        return {
            "status": "success",
            "data": analysis
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"分析简历失败: {str(e)}"
        )

@router.get("/resume/optimization/{candidate_id}")
async def get_resume_optimization(candidate_id: str):
    """获取简历优化建议"""
    try:
        candidate = await demo_loader.get_candidate_by_id(candidate_id)
        if not candidate:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="候选人不存在"
            )
        
        # 生成模拟的优化建议
        optimization = {
            "candidate_id": candidate_id,
            "current_score": random.randint(70, 90),
            "potential_score": random.randint(85, 95),
            "improvements": [
                {
                    "category": "技能关键词",
                    "priority": "高",
                    "suggestion": "添加更多与目标职位相关的技能关键词",
                    "examples": ["机器学习", "云计算", "微服务架构"]
                },
                {
                    "category": "项目经验",
                    "priority": "中",
                    "suggestion": "详细描述项目中的个人贡献和技术亮点",
                    "examples": ["使用Python优化算法性能提升30%", "负责团队协调和技术决策"]
                },
                {
                    "category": "格式优化",
                    "priority": "低",
                    "suggestion": "调整简历布局，突出重点信息",
                    "examples": ["使用清晰的段落结构", "突出核心技能和成就"]
                }
            ],
            "market_insights": {
                "hot_skills": ["Python", "AI/ML", "云原生", "DevOps"],
                "salary_trend": "上涨",
                "demand_level": "高"
            },
            "generated_at": datetime.now().isoformat()
        }
        
        return {
            "status": "success",
            "data": optimization
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取简历优化建议失败: {str(e)}"
        )

@router.get("/interview/preparation/{job_id}")
async def get_interview_preparation(
    job_id: str,
    candidate_id: str = Query("candidate_001", description="候选人ID")
):
    """获取面试准备建议"""
    try:
        job = await demo_loader.get_job_by_id(job_id)
        if not job:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="职位不存在"
            )
        
        # 生成模拟的面试准备建议
        preparation = {
            "job_id": job_id,
            "job_title": job["title"],
            "company": job["company"],
            "preparation_guide": {
                "technical_questions": [
                    f"请描述您在{job['required_skills'][0]}方面的项目经验",
                    f"如何处理{job['required_skills'][1]}相关的技术挑战？",
                    "您最擅长的技术栈是什么？请举例说明。",
                    "描述一个您解决过的复杂技术问题"
                ],
                "behavioral_questions": [
                    "请介绍一下您最成功的项目经历",
                    "如何处理团队合作中的分歧？",
                    "您的职业规划是什么？",
                    "为什么选择我们公司？"
                ],
                "company_research": [
                    f"了解{job['company']}的主要业务和发展历程",
                    "研究公司最近的新闻和动态",
                    "了解行业发展趋势和竞争对手",
                    "准备询问面试官的问题"
                ],
                "preparation_timeline": {
                    "1周前": ["研究公司背景", "复习相关技术知识"],
                    "3天前": ["准备自我介绍", "梳理项目经历"],
                    "1天前": ["模拟面试练习", "准备面试材料"],
                    "面试当天": ["确认面试时间地点", "保持良好状态"]
                }
            },
            "success_tips": [
                "准时到达面试地点",
                "保持自信和积极的态度",
                "准备具体的项目案例",
                "展现学习能力和团队合作精神"
            ],
            "generated_at": datetime.now().isoformat()
        }
        
        return {
            "status": "success",
            "data": preparation
        }
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取面试准备建议失败: {str(e)}"
        )

@router.get("/applications/tracking")
async def get_application_tracking(
    candidate_id: str = Query("candidate_001", description="候选人ID")
):
    """获取申请进度追踪"""
    try:
        # 生成模拟的申请追踪数据
        applications = []
        jobs = await demo_loader.get_jobs(limit=5)
        
        statuses = ["已投递", "简历筛选中", "面试邀请", "面试完成", "offer发放"]
        
        for i, job in enumerate(jobs):
            application = {
                "application_id": f"app_{i+1:03d}",
                "job_id": job["id"],
                "job_title": job["title"],
                "company": job["company"],
                "applied_date": (datetime.now() - random.choice([1, 3, 7, 14, 21])).isoformat(),
                "status": random.choice(statuses),
                "progress_percentage": random.randint(20, 90),
                "next_step": random.choice([
                    "等待HR联系",
                    "准备技术面试",
                    "等待面试结果",
                    "薪资谈判阶段"
                ]),
                "feedback": random.choice([
                    "简历符合基本要求，进入下一轮",
                    "技术背景匹配，安排面试",
                    "面试表现良好，等待最终决定",
                    None
                ])
            }
            applications.append(application)
        
        tracking_summary = {
            "total_applications": len(applications),
            "pending_interviews": len([a for a in applications if "面试" in a["status"]]),
            "offers_received": len([a for a in applications if "offer" in a["status"]]),
            "success_rate": round(random.uniform(15, 35), 1)
        }
        
        return {
            "status": "success",
            "data": {
                "applications": applications,
                "summary": tracking_summary
            }
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取申请追踪失败: {str(e)}"
        )

@router.get("/dashboard/stats")
async def get_candidate_dashboard_stats(
    candidate_id: str = Query("candidate_001", description="候选人ID")
):
    """获取候选人仪表板统计数据"""
    try:
        stats = {
            "profile_views": random.randint(50, 200),
            "applications_sent": random.randint(5, 25),
            "interview_invitations": random.randint(2, 8),
            "offers_received": random.randint(0, 3),
            "profile_completion": random.randint(75, 95),
            "skill_match_average": random.randint(70, 90),
            "recent_activities": [
                {
                    "type": "profile_view",
                    "description": "简历被HR查看",
                    "company": "北京科技有限公司",
                    "date": (datetime.now() - random.choice([1, 2, 3])).isoformat()
                },
                {
                    "type": "application",
                    "description": "申请了Python开发工程师职位",
                    "company": "上海创新科技",
                    "date": (datetime.now() - random.choice([2, 4, 7])).isoformat()
                },
                {
                    "type": "interview",
                    "description": "收到面试邀请",
                    "company": "深圳智能科技",
                    "date": (datetime.now() - random.choice([3, 5, 10])).isoformat()
                }
            ]
        }
        
        return {
            "status": "success",
            "data": stats
        }
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取候选人统计数据失败: {str(e)}"
        )